from datetime import datetime

from flask_restful import abort
from sqlalchemy import func
from sqlalchemy.orm import validates, declared_attr

from apps.model.baseModel import BaseModel
from apps.model.serializeModel import model_to_dict, model_to_list
from comm.sqlalchemyConfig import db


class usersModel(BaseModel):
    """
    用户表
    """
    __tablename__ = 'tx_users'
    id = db.Column(db.String(100), primary_key=True, autoincrement=False,doc='id')
    code = db.Column(db.String(125), nullable=False,doc='用户编码')
    lessees_id = db.Column(db.String(100), db.ForeignKey('tx_lessees.id'),doc='归属租户')
    username = db.Column(db.String(125), nullable=False,doc='用户名')
    password = db.Column(db.String(125), nullable=False,doc='用户密码')
    type = db.Column(db.Integer, nullable=False,default=2,doc='用户类型',comment="1、管理员；2、普通用户")
    start_time = db.Column(db.DateTime, default=datetime.now, nullable=True, doc='启用日期')
    end_time = db.Column(db.DateTime, default=datetime.now, nullable=True, doc='停用日期')
    dep_id = db.Column(db.String(125), nullable=True,doc='归属部门')
    rem = db.Column(db.Text, nullable=True, default='', doc='备注')

    __table_args__ = (
        {"info": {"order_by": id.asc()}},
    )

    def __str__(self):
        return 'users:{}'.format(self.username)


    @classmethod
    def getListData(cls, args, filterList, page=1, pageSize=10, excludeFiledList=None):
        """
        重写列表查询
        args url传递的原参数
        filterList 组装过的参数
        page 页码
        pageSize 分页大小
        excludeFiledList 排除字段
        """

        if excludeFiledList is None:
            excludeFiledList = []
        objData = {}
        modelDataObj = cls.query.filter(*filterList).paginate(page=page, per_page=pageSize, error_out=False)
        result = model_to_list(modelDataObj, excludeFiledList)
        objData["total"] = modelDataObj.total  # 总记录数
        objData["has_next"] = modelDataObj.has_next  # 是否有下一页
        objData["has_prev"] = modelDataObj.has_prev  # 是否有上一页
        objData["page"] = modelDataObj.page  # 当前页
        objData["pages"] = modelDataObj.pages  # 总页数
        objData["pageSize"] = pageSize  # 分页大小
        objData["data"] = result  # 分页大小
        return objData

    @classmethod
    def getPkData(cls, pk, primarList, excludeFiledList=None):
        """
        重写pk查询
        pk url传递的参数
        primarList 主键拼接后的列表
        excludeFiledList 排除字段
        """
        # 查询数据
        result = cls.query.filter(func.concat(*primarList) == pk).first()
        if result == None:
            return None, "没有查询到数据"
        resultData = model_to_dict(result, excludeFiledList)
        return resultData, None


class permissionModel(db.Model):
    """
    权限表
    """
    __tablename__ = 'tx_permission'
    id = db.Column(db.String(100), primary_key=True, autoincrement=False,doc='id')
    funs_code = db.Column(db.String(100), db.ForeignKey('tx_funs.code'),doc='归属功能模块code')
    code = db.Column(db.String(100), nullable=False,unique=True,doc='权限code使用此作为存储----暂时无用')
    name = db.Column(db.String(125), nullable=False,unique=True,doc='权限名称')
    status = db.Column(db.Boolean, nullable=True, default=1, doc='是否启用')

class onLineModel(db.Model):
    # 在线用户表
    __tablename__ = 'tx_online'
    id = db.Column(db.String(100), primary_key=True, autoincrement=False, doc='id')
    user_id = db.Column(db.String(100), nullable=False,unique=True, doc='用户ID')
    lessees_id = db.Column(db.String(100), nullable=False, doc='租户ID')
    username = db.Column(db.String(125), nullable=False, doc='用户名称')
    token = db.Column(db.String(1000), nullable=False, doc='token')
    ip = db.Column(db.String(250), nullable=False, doc='登录地址')
    create_time = db.Column(db.DateTime, default=datetime.now, nullable=True)

    @classmethod
    def getPkData(cls, pk):
        result = cls.query.filter(cls.id == pk).first()
        if result == None:
            return None, '用户在线中'
        return None, None

    @classmethod
    def deletePkData(cls, args):
        try:
            db.session.query(cls).filter_by(**args).delete()
            db.session.commit()
        except Exception as e:
            return None, '下线失败' + repr(e)
        return None, None

    @classmethod
    def countLesseesData(cls, lessees_id):
        result = cls.query.filter(cls.lessees_id == lessees_id).count()
        return result
